//
//  DYSMSCenter.h
//  singlePushDemo
//
//  Created by JM on 15/10/10.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "DYSMSCenter.h"

static NSMutableDictionary *_subscriptionDictionary = nil;

@implementation DYSMSCenter

+ (void)initialize {
    
    if (self == [DYSMSCenter class]) {
        
        _subscriptionDictionary = [NSMutableDictionary dictionary];
    }
}

+ (void)createSMSType:(NSString *)aSMSType {

    NSParameterAssert(aSMSType);
    
    NSHashTable *hashTable = [self existaSMSType:aSMSType];
    if (hashTable == nil) {
        
        hashTable = [NSHashTable weakObjectsHashTable];
        [_subscriptionDictionary setObject:hashTable forKey:aSMSType];
    }
}

+ (void)removeSMSType:(NSString *)aSMSType {

    NSParameterAssert(aSMSType);
    
    NSHashTable *hashTable = [self existaSMSType:aSMSType];
    if (hashTable) {
        
        [_subscriptionDictionary removeObjectForKey:aSMSType];
    }
}

+ (void)addRecever:(id <DYSMSProtocol>)receiver withSMSType:(NSString *)aSMSType {

    NSParameterAssert(receiver);
    NSParameterAssert(aSMSType);
    
    NSHashTable *hashTable = [self existaSMSType:aSMSType];
    [hashTable addObject:receiver];
}

+ (void)removeReceiver:(id <DYSMSProtocol>)receiver withSMSType:(NSString *)aSMSType {

    NSParameterAssert(aSMSType);
    
    NSHashTable *hashTable = [self existaSMSType:aSMSType];
    [hashTable removeObject:receiver];
}

+ (void)sendMessage:(id)message byType:(NSString *)aSMSType {

    NSParameterAssert(aSMSType);
    
    NSHashTable *hashTable = [self existaSMSType:aSMSType];
    if (hashTable) {
        
        NSEnumerator *enumerator = [hashTable objectEnumerator];
        id <DYSMSProtocol> object = nil;
        while (object = [enumerator nextObject]) {
            
            if ([object respondsToSelector:@selector(didReceiveMessage:withtype:)]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [object didReceiveMessage:message withtype:aSMSType];
                });
            }
        }
    }
}

#pragma mark - 私有方法
+ (NSHashTable *)existaSMSType:(NSString *)aSMSType {
    return _subscriptionDictionary[aSMSType];
}

@end
